<template>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    width="65%"
    :show-close="false"
    :visible.sync="visible">
    <el-form  :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="160px">
      <el-form-item style="width:100%" class="oneCls" label="英文名称：" prop="interfaceName">
        <el-input style="width:90%" @input="changeUserInput(dataForm.interfaceName)" v-model="dataForm.interfaceName" placeholder="请输入英文名称"></el-input>
        <p class="info">
          <span>说明：输入的内容是纯英文，包含大小写</span>
          <span style="color:red;">{{ textInfo }}</span>
        </p>
        <el-button :disabled="isYzFlag" :type="isYzFlag?'success':'primary'" @click="yzParmData(dataForm.interfaceName)">
          <span v-if="isYzFlag"><i class="el-icon-success"></i> 通过</span>
          <span v-else><i class="el-icon-menu"></i>验证</span>
        </el-button>
      </el-form-item>
      <el-form-item  v-if="isYzFlag" label="接口中文名：" prop="name">
        <el-input v-model="dataForm.name" placeholder="请输入接口中文名"></el-input>
        <p class="info"></p>
      </el-form-item>
      <el-form-item  v-if="isYzFlag" label="接口地址：" prop="url">
        <el-input v-model="dataForm.url" placeholder="请输入接口地址"></el-input>
        <p class="info"></p>
      </el-form-item>
      <!-- <el-form-item  v-if="isYzFlag" label="请求头参数：" prop="heard">
        <el-input v-model="dataForm.heard" placeholder=""></el-input>
        <p class="info">说明：请求头的参数，JSON格式</p>
      </el-form-item> -->
      <el-form-item  v-if="isYzFlag" label="是否需要token：" prop="needToken">
        <el-radio v-model="dataForm.needToken" label="1">是</el-radio>
        <el-radio v-model="dataForm.needToken" label="2">否</el-radio>
      </el-form-item>
      <el-form-item  v-if="isYzFlag&&dataForm.needToken=='1'" label="所需token：" prop="tokenId">
        <el-select v-model="dataForm.tokenId" placeholder="请选择所需token">
            <el-option
              v-for="(item,i) in pageIdList"
              :key="i"
              :label="item.value"
              :value="item.key">
            </el-option>
          </el-select>
        <p class="info">说明：选择配置好的token</p>
      </el-form-item>
      <el-form-item  v-if="isYzFlag&&dataForm.needToken=='1'" label="token放置位置：" prop="tokenPath">
        <el-input v-model="dataForm.tokenPath" placeholder="请输入token放置位置"></el-input>
        <p class="info">说明：token放置的位置，一般是请求头里面，也有请求体：示例param,heard,body</p>
      </el-form-item>
      <el-form-item  v-if="isYzFlag&&dataForm.needToken=='1'" label="token参数名称：" prop="tokenData">
        <el-input v-model="dataForm.tokenData" placeholder="请输入token参数名称"></el-input>
        <p class="info">说明：token参数名称，如："Authorization、token"</p>
      </el-form-item>
      <el-form-item  v-if="isYzFlag&&dataForm.needToken=='1'" label="token默认前缀：" prop="tokenPrefix">
        <el-input v-model="dataForm.tokenPrefix" placeholder="请输入token默认前缀"></el-input>
        <p class="info">说明：token前缀，不填默认是空字符，如：Bearer </p>
      </el-form-item>
      <el-form-item  v-if="isYzFlag" label="请求类型：" prop="method">
        <el-tag
          style="margin-right:10px;cursor: pointer;"
          v-for="(tag,index) in methodsList"
          @click="selecttag(tag,index)"
          :key="index"
          :type="tag.type">
          {{tag.name}}
        </el-tag>
      </el-form-item>
      <el-form-item  v-if="isYzFlag" label="参数所处位置：" prop="dataPath">
        <el-input v-model="dataForm.dataPath" placeholder="请输入参数所处位置"></el-input>
        <p class="info">说明：获取数据的路径，详细地址，用"."隔开，如"data.contents"</p>
      </el-form-item>
      <el-form-item  v-if="isYzFlag" label="url参数：" prop="param">
        <el-input v-model="dataForm.param" placeholder="请输入token默认前缀"></el-input>
        <p class="info">说明：url里面的参数</p>
      </el-form-item>
      <el-form-item  v-if="isYzFlag" label="是否取第一条：" prop="firstOne">
        <el-radio v-model="dataForm.firstOne" label="1">是</el-radio>
        <el-radio v-model="dataForm.firstOne" label="2">否</el-radio>
      </el-form-item>
      <el-form-item  v-if="isYzFlag" label="是否需要key值替换：" prop="keyReplace">
        <el-radio v-model="dataForm.keyReplace" label="1">是</el-radio>
        <el-radio v-model="dataForm.keyReplace" label="2">否</el-radio>
      </el-form-item>
      <!-- <el-form-item  v-if="isYzFlag" label="需要替换的值：" prop="keyReplaceValue">
        <el-input v-model="dataForm.keyReplaceValue" placeholder=""></el-input>
        <p class="info">说明：字段说明信息</p>
      </el-form-item> -->
      <el-form-item  v-if="isYzFlag" label="是否需要缓存：" prop="redisNeed">
        <el-radio v-model="dataForm.redisNeed" label="1">是</el-radio>
        <el-radio v-model="dataForm.redisNeed" label="2">否</el-radio>
      </el-form-item>
      <el-form-item  v-if="isYzFlag" label="接口返回数据类型：" prop="dataType">
        <el-input v-model="dataForm.dataType" placeholder="请输入token默认前缀"></el-input>
          <p class="info">说明：接口返回数据类型： ArrayList、LinkedHashMap、String</p>
      </el-form-item>
      <el-form-item  v-if="isYzFlag" label="备注：" prop="remark">
        <el-input :rows="4" type="textarea" v-model="dataForm.remark" placeholder=""></el-input>
      </el-form-item>
      <el-form-item  v-if="isYzFlag" label="body参数：" prop="jsonBody">
        <el-input :rows="4" @focus="editJson('jsonBody',dataForm.jsonBody)"  type="textarea" v-model="dataForm.jsonBody" placeholder=""></el-input>
        <p class="info" style="top:78px;">说明：接口请求的body参数</p>
      </el-form-item>
      <el-form-item  v-if="isYzFlag" label="请求头：" prop="jsonHeard">
        <el-input :rows="4" @focus="editJson('jsonHeard',dataForm.jsonHeard)"  type="textarea" v-model="dataForm.jsonHeard" placeholder=""></el-input>
        <p class="info" style="top:78px;">说明：请求头的参数，JSON格式</p>
      </el-form-item>
      <el-form-item  v-if="isYzFlag&&dataForm.keyReplace=='1'" label="key值替换字符串：" prop="jsonKeyReplaceValue">
        <el-input :rows="4" type="textarea" @focus="editJson('jsonKeyReplaceValue',dataForm.jsonKeyReplaceValue)" v-model="dataForm.jsonKeyReplaceValue" placeholder=""></el-input>
        <p class="info" style="top:78px;">说明：需要替换的字符，若是否key值替换选择是，才输入</p>
      </el-form-item>
    </el-form>
    <div style="padding-left:60px;color:#17B3A3;word-wrap: break-word;word-break: normal;" v-if="veriicationStr!=''"><span>验证成功：</span>{{veriicationStr}}</div>
    <span  slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>



    <el-dialog
      width="30%"
      title="JSON参数编辑"
      :visible.sync="editPostJsonFlag"
      append-to-body>
      <div v-if="editPostJsonFlag">
        <vue-json-editor
          v-model="resultInfo"
          :showBtns="false"
          :mode="'code'"
          @json-change="onJsonChange"
          @json-save="onJsonSave"
          @has-error="onError"
        />
        <br>
      <el-button type="primary" @click="checkJson">确定</el-button>
    </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
    import request from '@/utils/request'
  import Vue from 'vue'
  import vueJsonEditor from 'vue-json-editor'
  import { getToken, setToken, removeToken } from '@/utils/auth'
  export default {
    components:{
      vueJsonEditor
    },
    data () {
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('英文名称不能为空'));
        } else {
          callback();
        }
      };
      return {
        title:"",
        pageIdList:[],
        textInfo:"",
        isYzFlag:false,
        conmitFormData:null,
        jsonType:'',
        veriicationStr:"",
        hasJsonFlag:true,  // json是否验证通过
        // json数据
        resultInfo: {},

        methodsList: [],
        options: [],
        editPostJsonFlag: false,
        // -------------
        visible: false,
        menuList: [],
        menuListTreeProps: {
          label: 'name',
          children: 'children'
        },
        dataForm: {
          interfaceName: '',
          name:"",
          url:"",
          heard:"",
          needToken:"",
          tokenId:"",
          tokenPath:"",
          tokenData:"",
          tokenPrefix:"",
          method:"",
          dataPath:"",
          body: '',
          param:"",
          firstOne:"",
          keyReplace:"",
          keyReplaceValue:"",
          redisNeed:"",
          dataType:"",
          remark:"",
          jsonBody:"",
          jsonHeard:"",
          jsonKeyReplaceValue:""
        },
        dataRule: {}
      }
    },
    methods: {
      changeRadio(){
       if(this.dataForm.needToken=='1'){

       }
      },
      changeUserInput(v){
        this.isYzFlag = false
        if(v.length==0){
          this.textInfo = '请先输入英文名称'
          return
        }else{
          this.textInfo = ''
        }
        //清空所有字段数据
      },
      resetData(){
        this.methodsList.forEach((item,index)=> {
          item.type = ""
        })
        this.dataForm= {
          interfaceName: this.dataForm.interfaceName,
          name:"",
          url:"",
          heard:"",
          needToken:"",
          tokenId:"",
          tokenPath:"",
          tokenData:"",
          tokenPrefix:"",
          method:"",
          dataPath:"",
          body: '',
          param:"",
          firstOne:"",
          keyReplace:"",
          keyReplaceValue:"",
          redisNeed:"",
          dataType:"",
          remark:"",
          jsonBody:"",
          jsonHeard:"",
          jsonKeyReplaceValue:""
        }
      },
      yzParmData(v){
        if(!v||v.length==0){
          this.textInfo = '请先输入英文名称'
          return
        }
        if(this.isYzFlag){
          return
        }
        request({
          url: '/ht-datadevelop/api/real/manage/getInterfaceNameCompliance',
          method: 'post',
          data:{interfaceName:v}
        }).then((res) => {
          if(res.data.success){
            this.isYzFlag = true
            this.textInfo = ""
            this.resetData()
          }else{
            this.textInfo = "【"+res.data.message+"】"
          }
        })
      },
      closeDialog(){
        this.veriicationStr=''
        this.dataForm = {
          interfaceName: '',
          url: '',
          method: '0',
          contentType: '',
          keyPath: '',
          body: '',
          parameter: '',
          status:'',
          inlay:'',
          heardData:'',
          inlayParameter:'',
          bodyData:''
        }
        this.resultInfo = {}
        this.visible = false
        this.$refs['dataForm'].resetFields()
      },
      verification(){
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            let params = JSON.parse(JSON.stringify(this.dataForm))
            params.body = ""
            params.bodyData = params.bodyData?JSON.parse(params.bodyData):''
            params.heardData = params.heardData?JSON.parse(params.heardData):''
            this.conmitFormData = JSON.parse(JSON.stringify(params))

            request({
              url: `/ht-datadevelop/token/manage/getApiTokenCheck`,
              method: 'post',
              data: this.conmitFormData
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.veriicationStr = data.token
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      onJsonChange (value) {
        // 实时保存
        this.onJsonSave(value)
      },
      onJsonSave (value) {
        this.resultInfo = value
        this.hasJsonFlag = true
      },
      onError(value) {
        this.hasJsonFlag = false
      },
      // 检查json
      checkJson(){
        this.dataForm[this.jsonType] = JSON.stringify(this.resultInfo)
        this.editPostJsonFlag = false
        return true
      },
      editJson (v,jsonObj) {
        if(jsonObj){
          this.resultInfo = JSON.parse(jsonObj) //json编辑器数据
        }else{
          this.resultInfo = {}
        }
        this.jsonType = v
        this.editPostJsonFlag = true
      },
      selecttag (tag, i) {
        this.methodsList.forEach((item,index)=> {
          item.type = ""
        })
        this.methodsList[i].type = "warning"
        this.dataForm['method'] = tag.name
      },
      editData(v){
        if(v.add){
          //这里是新增
          this.isYzFlag = false
        }else{
          this.isYzFlag = true //修改显示字段
        }
        this.visible = true
        this.dataForm = JSON.parse(JSON.stringify(v)) //复制编辑对象数据

        this.dataForm.jsonBody = v.jsonBody?JSON.stringify(v.jsonBody):null //用来显示的字符串数据
        this.dataForm.jsonHeard =v.jsonHeard?JSON.stringify(v.jsonHeard):null //用来显示的字符串数据
        this.dataForm.jsonKeyReplaceValue =v.jsonKeyReplaceValue?JSON.stringify(v.jsonKeyReplaceValue):null

        this.methodsList.forEach((item,index)=> {
          if(item.name==v.method){
            item.type = "warning"
          }
        })
      },
      init (row) {
        if(row.add){
          this.title = '新增'
        }else{
          this.title = '修改'
        }
        request({
          url: '/ht-datadevelop/sys/common/getContentTypeList',
          method: 'get',
          params:{}
        }).then((res) => {
           this.visible = true
           this.options = res.data
        })
        request({
          url:'/ht-datadevelop/token/manage/listToken',
          method: 'get',
          params:{}
        }).then((res) => {
          this.pageIdList  = res.data
        })
        request({
          url: '/ht-datadevelop/sys/common/getRequestMethodList',
          method: 'get',
          params:{token:getToken()}
        }).then((res) => {
          this.methodsList  = []
          res.data.forEach((item,index)=>{
            this.methodsList.push({
              name:item,
              type:''
            })
          })
          if(row){
            this.editData(row)
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        if(!this.isYzFlag){
          return 
        }
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            let param = JSON.parse(JSON.stringify(this.dataForm))
            param.jsonBody = param.jsonBody==''?null:JSON.parse(param.jsonBody)
            param.jsonHeard = param.jsonHeard==''?null:JSON.parse(param.jsonHeard)
            param.jsonKeyReplaceValue = param.jsonKeyReplaceValue==''?null:JSON.parse(param.jsonKeyReplaceValue)
            request({
              url:`/ht-datadevelop/api/real/manage/saveOrUpdate`,
              method: 'post',
              data: param
            }).then((res) => {
              if (res.code === 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 500,
                  onClose: () => {
                    this.closeDialog()
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        })
      }
    }
  }
</script>


<style lang="scss" scoped>
  .oneCls{
    >div{
      position: relative;
      >button{
        position: absolute;
        right: 0;
      }
    }
  }
>>>.el-form-item__content{
  position: relative;
}
>>>.el-textarea__inner{
  min-height:220px !important;
  max-height:220px !important;
}
>>>.info{
    position: absolute;
    left: 0;
    top:26px;
    font-size: 10px;
    width:100%;
    color: #ef9001;
  }
  >>>.el-select{
    display: block !important;
  }
  .el-form{
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
  }
  .el-form-item{
    width: 50%;
  }
  .el-form-item:nth-child(1){
    .el-input{
      width:75%;
    }
  }
 ul{
  margin-left: 0 !important;
  padding-left: 0 !important;
  .lis{
    margin-bottom: 6px;
    list-style: none;
    display: flex;
    span:nth-child(1){
      width: 45%;
    }
    span:nth-child(2){
      width: 45%;
    }
    span:nth-child(3){
      width: 10%;
      text-align: center;
      padding-top: 6px;
      cursor: pointer;
      color: red;
    }
    span{
      display: block;
      >>>.el-input{
        display: inline-block;
        width:80%;
      }
    }
  }
 }
</style>
